package com.neuronbit.businessflow.intellij.ui.projectView;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.RefactoringActionHandlerFactory;
import com.intellij.refactoring.rename.RenameHandler;
import org.jetbrains.annotations.NotNull;

/**
 * The type Flow rename handler.
 */
public class FlowRenameHandler implements RenameHandler {
    @Override
    public boolean isAvailableOnDataContext(@NotNull DataContext dataContext) {
        Flow[] flows = Flow.DATA_KEY.getData(dataContext);
        return flows != null && flows.length == 1;
    }

    @Override
    public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
        Flow[] flows = Flow.DATA_KEY.getData(dataContext);
        if (flows == null || flows.length != 1) return;
        PsiClass boundClass = flows[0].getClassToBind();
        RefactoringActionHandlerFactory.getInstance()
                .createRenameHandler()
                .invoke(project, new PsiElement[]{boundClass}, dataContext);
    }

    @Override
    public void invoke(@NotNull Project project, PsiElement @NotNull [] elements, DataContext dataContext) {
        invoke(project, null, null, dataContext);
    }
}
